package de.sordul.jobMaster.util;

import javax.servlet.ServletRequest;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

/**
 * Prevents the called method to be executed when call comes from outside the server
 * it is hosted on.
 */
public class LocalOnlyInterceptor implements MethodInterceptor  {

	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		ServletRequest request = null;
		
		// Check if there is a ServletRequest in the arguments, throw an exception if not
		Object[] methodArguments = invocation.getArguments();
		for(Object argument: methodArguments) {
			if(argument instanceof  javax.servlet.ServletRequest) {
				request = (ServletRequest) argument;
			}
		}
		if(request == null) {
			throw new IllegalStateException(invocation.getMethod().getName() + " - No ServletRequest contained!");
		
		} else {
			
			// Local call? - proceed
			if( request.getRemoteHost().equals( request.getServerName() ) || 
				request.getRemoteAddr().equals("0:0:0:0:0:0:0:1") && request.getServerName().equals("localhost") ) {
				
				return invocation.proceed();
			}
					
			// Non-local call - Return NULL
			return null;
		}
	}

}
